package com.zmc.coupon.infrastructure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmc.common.utils.StringUtils;
import com.zmc.common.utils.token.AuthTokenService;
import com.zmc.coupon.infrastructure.bean.query.CouponQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmc.common.utils.PageUtils;
import com.zmc.common.utils.Query;

import com.zmc.coupon.infrastructure.dao.CouponDao;
import com.zmc.coupon.infrastructure.entity.CouponEntity;
import com.zmc.coupon.infrastructure.service.CouponService;


/**
 * @author zmc
 */
@Service("couponService")
public class CouponServiceImpl extends ServiceImpl<CouponDao, CouponEntity> implements CouponService {

    @Autowired
    private AuthTokenService authTokenService;

    @Override
    public PageUtils queryPage(CouponQuery query) {
        Page<CouponEntity> page = baseMapper.selectPage(new Page<>(query.getPageNum(), query.getPageSize()), getWrapper(query));
        return new PageUtils(page);
    }

    @Override
    public List<CouponEntity> queryList(CouponQuery query) {
        return list(getWrapper(query));
    }

    @Override
    public boolean receiveCoupon(Long couponId) {
        return baseMapper.receiveCoupon(couponId);
    }

    @Override
    public void updateUseCount(Map<Long, Long> couponMap) {
        baseMapper.updateUseCount(couponMap);
    }

    public LambdaQueryWrapper<CouponEntity> getWrapper(CouponQuery query) {
        LambdaQueryWrapper<CouponEntity> wrapper  = new LambdaQueryWrapper<>();
        wrapper.eq(CouponEntity::getMerchantId,  authTokenService.getUserInfo().getMerchantId())
                .eq(StringUtils.isNotEmpty(query.getCouponName()), CouponEntity::getCouponName, query.getCouponName())
                .orderByDesc(CouponEntity::getCreateTime);
        return wrapper;
    }

}